package foundation.filter;


import model.sys.Const;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.http.message.BasicNameValuePair;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author futao
 * Created on 18-7-23-上午10:24.
 */
public class AppFilter implements javax.servlet.Filter {
    public int count = 0;

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        count++;
        System.out.println("访问人数:" + count);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        /*cookies有可能为null*/
        Cookie[] cookies = request.getCookies();
        /*设置request编码格式*/
        request.setCharacterEncoding("UTF-8");
        boolean shaoBing = false;
        /*
         * cookie是会话级别的，当用户关闭浏览器，cookie就被清除了。
         * 后端无法做到cookie的删除，只能覆盖或者设置过期时间
         * setMaxAge(0)
         * setValue("")
         * */
        /*获取上一次访问时间*/
        if (cookies != null && cookies.length >= 1) {
            for (Cookie cookie : cookies) {
                if ("lastVisitTime".equals(cookie.getName())) {
                    shaoBing = true;
                    /*可以在用户logout的时间更新这个时间*/
                    System.out.println("你上次访问的时间是：" + URLDecoder.decode(cookie.getValue(), String.valueOf(Charsets.UTF_8)));
                }
            }
        } else {
            ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
            BasicNameValuePair cookieName = new BasicNameValuePair("lastVisitTime", DateFormatUtils.format(new Date(), Const.TIME_STAMP_FORMATTER));
            BasicNameValuePair maxAge = new BasicNameValuePair("maxAge", String.valueOf(24 * 60 * 60));
            arrayList.add(cookieName);
            /*时间为秒*/
            arrayList.add(maxAge);
            setCookie(response, arrayList);
            System.out.println("您是第一次访问本站，当前时间是：" + DateFormatUtils.format(new Date(), Const.TIME_STAMP_FORMATTER));
        }

        if (!shaoBing) {
            ArrayList<BasicNameValuePair> arrayList = new ArrayList<BasicNameValuePair>();
            BasicNameValuePair cookieName = new BasicNameValuePair("lastVisitTime", DateFormatUtils.format(new Date(), Const.TIME_STAMP_FORMATTER));
            BasicNameValuePair maxAge = new BasicNameValuePair("maxAge", String.valueOf(24 * 60 * 60));
            arrayList.add(cookieName);
            arrayList.add(maxAge);
            setCookie(response, arrayList);
            System.out.println("您是第一次访问本站，当前时间是：" + DateFormatUtils.format(new Date(), Const.TIME_STAMP_FORMATTER));
        }
        response.setCharacterEncoding("UTF-8");
        System.out.println("====" + request.getRequestURL());
        filterChain.doFilter(request, response);
    }

    private void setCookie(HttpServletResponse response, ArrayList<BasicNameValuePair> basicNameValuePairs) throws UnsupportedEncodingException {
        /*通过addCookie的方式不能实现，会报错*/
        /*jetty不能通过addCookie的方式添加cookie，只能通过setHeader的方式添加cookie.
         * tomcat可以通过addCookie的方式添加cookie
         * */
//        Cookie cookie = new Cookie("lastVisitTime", DateFormatUtils.format(new Date(), Const.TIME_STAMP_FORMATTER));
//        cookie.setMaxAge(24 * 60 * 60);
//        response.addCookie(cookie);
        StringBuilder cookie = new StringBuilder();
        for (BasicNameValuePair basicNameValuePair : basicNameValuePairs) {
            cookie.append(URLEncoder.encode(basicNameValuePair.getName(), String.valueOf(Charsets.UTF_8)))
                  .append("=").append(URLEncoder.encode(basicNameValuePair.getValue(), String.valueOf(Charsets.UTF_8)))
                  .append(";");
        }
        response.setHeader("Set-Cookie", String.valueOf(cookie));
    }

    @Override
    public void destroy() {

    }
}
